<?php
/*
*All rights reserved: Json.
*Links:http://www.liyaoquan.cn.
*Links:http://imarkchina.cn.
*Links:http://www.imarkchina.cn.
*/

/**
 * 博客前后台公共模型，负责数据，增，删，改，查
 * 因为没有博客数据没使用数据库，所以没有继承 Model 类
 */
Class PublicModel{

	/**
	 * 取博客配置文件
	 * @return [type] [description]
	 */
	Public function blogConfig(){
		return loadfile(C('config'));
	}

	/**
	 * 取服务器信息
	 * @return [type] [description]
	 */
	Public function systemInfo(){
		return getSystemInfo();
	}

	/**
	 * 取博客广告数据
	 * @return [type] [description]
	 */
	Public function blogAd(){
		return loadfile(C('ad'));
	}

	/**
	 * 日志数据处理（前台）
	 * @return [type] [description]
	 */
	Public function getPost(){
		$dir = C('post.postid');
		$Fdata = GetFileList($dir);
		$temp = array();
		foreach ($Fdata as $v) {
			$temp[] = loadfile($dir.$v);
		}
		$temp = Arr::getArray($temp);
		uasort($temp, 'Post_Sort');
		$array = array();
		foreach ($temp as $k => $v) {
			$array[][$k] = $v;
		}
		return $array;
	}



	/**
	 * 处理日志（后台）
	 */
	Public function AllPostData($check = false){
		if ($check) {
			$dir = C('post.postrecovery');
		} else {
			$dir = C('post.postid');
		}
		$Fdata = GetFileList($dir);
		$data = array();
		foreach ($Fdata as $v) {
			$data[] = loadfile($dir.$v);
		}
		$data = Arr::getArray($data);
		uasort($data, 'Post_Sort');
		return $data;
	}

	/**
	 * 专题数据处理
	 * @return [type] [description]
	 */
	Public function getPage(){
		$dir = C('page.data');
		$id = loadfile(C('page.id'));
		uasort($id, 'List_Sort');
		$array = array();
		foreach ($id as $k => $v) {
			$array[] = unfile($dir.$v['id'].'.Mark');
		}
		return $array;
	}

	/**
	 * 处理博客分类数据
	 * @return [type] [description]
	 */
	Public function getListData(){
		$list = loadfile(C('post.listid'));
		$listarr = array();
		foreach ($list as $k => $v) {
			$listarr[$k]= $v['title'];
		}
		return $listarr;
	}

	/**
	 * 处理所有评论ID文件
	 * @return [type] [description]
	 */
	Public function getPingLun(){
		$files = GetFileList(C('pinglun.id'));
		$data = array();
		foreach ($files as $v){
			$check = loadfile(C('pinglun.id').$v);
			if (empty($check)) {
				continue;
			}
			$data[] = $check;
		}
		$data = Arr::getArray($data);
		uasort($data, 'Post_Sort');
		return $data;
	}

	/**
	 * 前台定义日志需要取那些字段，加快速度
	 * @param  [type] $array [接收数组]
	 * @return [type]        [description]
	 */
	Public function getunFile($array){
		if (empty($array)) {
			return;
		}
		foreach($array as $k => $v){
			$data[$k] = array(
				'id' => $v['id'],
				'title' => $v['title'],
				'date' => $v['date'],
				'listid' => $v['listid'],
				'list' => $v['list'],
				'tags' => $v['tags'],
				'des' => $v['des'],
				'sdate' => $v['sdate'],
				);
			if (!empty($v['imagesurl'])) {
				$data[$k]['imagesurl'] = $v['imagesurl'];
			} else {
				$data[$k]['imagesurl'] = '';
			}
		}
		return $data;
	}

	/**
	 * 后台定义专题需要取那些字段，加快速度
	 * @param  [type] $array [description]
	 * @return [type]        [description]
	 */
	Public function getunPage($array){
		if (empty($array)) {
			return;
		}
		foreach ($array as $k => $v) {
			$data[$k] = array(
				'id' => $v['id'],
				'title' => $v['title'],
				'date' => $v['date'],
				'time' => $v['time'],
				'ord' => $v['ord'],
				'index_show' => $v['index_show'],
				);
		}
		return $data;
	}

	/**
	 * 后台定义用户数据需要取那些字段，加快速度
	 * @param  [type] $array [description]
	 * @return [type]        [description]
	 */
	Public function getUsers($array){
		if (empty($array)) {
			return array();
		}
		foreach ($array as $k => $v) {
			$data[$k] = array(
				'username' => $v['username'],
				'user_id' => $v['user_id'],
				'talk' => $v['talk'],
				'regtime' => $v['regtime'],
				'ord' => $v['ord'],
				);
		}
		uasort($data, 'Users_Sort');
		return $data;
	}

	/**
	 * 后台定义日志需要取那些字段，加快速度
	 * @param  [type] $array [接收数组]
	 * @return [type]        [description]
	 */
	Public function RgetunFile($array){
		if (empty($array)) {
			return array();
		}
		foreach($array as $k=>$v){
			$data[$k]=array(
				'id' => $v['id'],
				'title' => $v['title'],
				'date' => $v['date'],
				'time' => $v['time'],
				'listid' => $v['listid'],
				'list' => $v['list'],
				'tags' => $v['tags'],
				);
		}
		return $data;
	}

	/**
	 * 替换评论中表情
	 * @param  [type] $array [接收数据]
	 * @return [type]        [description]
	 */
	Public function msgReplace($string){
		return preg_replace('[\[msg_([0-9]*)\]]', '<img style="width: 20px;height: 20px;" src="'.DOMAIN.ROOT_URL.'/Public/Resources/PingLun_Msg/$1.gif" />', $string);
	}


	/**
	 * 发送邮件评论内容
	 * @param [type] $data [description]
	 */
	Public function ReEmail($data, $check = false){
		if ($check || is_array($data)) {
			$mail = new Phpmailer();
			$mail->isSMTP();
			$mail->SMTPAuth = true;
			$mail->Host = $data['host'];
			$mail->Username = $data['username'];
			$mail->Password = $data['password'];
			$mail->From = $data['from'];
			$mail->FromName = $data['fromname'];
			$mail->SMTPSecure = 'ssl';
			$mail->Port = 465;
			$mail->CharSet = 'UTF-8';
			$mail->isHTML(true);
			$mail->addAddress('admin@liyaoquan.cn', $data['rename']);
			$mail->Subject = $data['blogtitle'];
			$mail->Body = $data['content'];
			$mail->send();
		}
	}

	/**
	 * 百度自动推送并写入到日志
	 * @param [type] $urls  [description]
	 * @param [type] $token [description]
	 */
	Public function BaiDuPost($urls, $token){
		$api = 'http://data.zz.baidu.com/urls?site='.str_replace('http://','' , DOMAIN).'&token='.$token.'&type=original';
		$ch = curl_init();
		$options =  array(
			CURLOPT_URL => $api,
			CURLOPT_POST => true,
			CURLOPT_RETURNTRANSFER => true,
			@CURLOPT_POSTFIELDS => @implode("\n", $urls),
			CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
			);
		curl_setopt_array($ch, $options);
		$result = curl_exec($ch);
		$json = json_decode($result);
		$baidu_remain = $json -> {'remain'};
		$baidu_success = $json -> {'success'};
		if ($baidu_success != 0) {
			RLOG('成功推送日志到百度服务器~！推送成功：'.$baidu_success.'条~！今天剩余：'.$baidu_remain.'条~！', 'baidusuccess');
		} else {
			RLOG('推送日志到百度服务器失败~！请查看：http://zhanzhang.baidu.com/college/courseinfo?id=267&page=2#h2_article_title12  错误代码：'.$result, 'baiduerror');
		}
	}

	/**
	 *检查相关设置是否开启
	 */
	Public function CheckIsOpen(){
		$C = $this->blogConfig();
		$redata = array();
		$redata['fdlinks'] = ($C['fdlinks'] == 'open') ? true : false;
		$redata['istop'] = ($C['top_posts'] == 'open') ? true : false;
		$adfile = loadfile(C('ad'));
		$redata['ad_index'] = (!empty($adfile['ad_index'])) ? true : false;
		$redata['ad_index_1'] = (!empty($adfile['ad_index_1'])) ? true : false;
		$redata['ad_archive'] = (!empty($adfile['ad_archive'])) ? true : false;
		$redata['ad_archive_1'] = (!empty($adfile['ad_archive_1'])) ? true : false;
		$redata['ad_page'] = (!empty($adfile['ad_page'])) ? true : false;
		$redata['ad_post_1'] = (!empty($adfile['ad_post_1'])) ? true : false;
		$redata['ad_post_2'] = (!empty($adfile['ad_post_2'])) ? true : false;
		$redata['ad_post_3'] = (!empty($adfile['ad_post_3'])) ? true : false;
		$redata['ad_index_show'] = (!empty($adfile['ad_index_show'])) ? true : false;
		return $redata;
	}

	/**
	*处理百度上传配置Json文件
	 */
	Public function putJsonFile(){
		$json_file = ROOT_PATH.C('edit').'php/config.json';
		$edit_json = json_decode(preg_replace('/\/\*[\s\S]+?\*\//', '', file_get_contents($json_file)), true);
		$last_json = array_merge((array)$edit_json, (array)C('ROOTUPLOAD'));
		$result =  json_encode($last_json);
		file_put_contents($json_file, $result);
	}
}